<!DOCTYPE html>
<html lang="en">
<head>
    <title>Audio+Video+Screen Sharing using RTCMultiConnection</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <meta name="description" content="Audio+Video+Screen Sharing using RTCMultiConnection" />
    <meta name="keywords" content="WebRTC,RTCMultiConnection,Demos,Experiments,Samples,Examples" />
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="./css/style.css">
</head>
<body>
    <div class="wraper nav">
        <header class="header navbar navbar-dark bg-dark">
            <div class="logo">VideoChat</div>
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">房间号：</span>
                </div>
                <input type="text"  id="room-id" autocorrect=off autocapitalize=off size=20 class="form-control" placeholder="房间号" aria-describedby="basic-addon1" disabled>
                <div class="input-group-append">
                <button type="button" class="btn btn-gray" id="open-room">打开房间</button>
                <!-- <button id="share-screen" disabled>Share Screen</button> -->
                </div>
            </div>
        </header>
        <div class="content container-fluid">
            <div class="row">
                <div class="me-area">
                    <div class="name">昵称：<span id="userName">小米</span></div>
                    <div id="me-videos-container"></div>
                </div>
                <div class="video-area">
                    <div id="videos-container"></div>
                </div>
                <div class="chat-area">
                    <div class="chatbox chatbox-master">
                        <div class="chat-head clearfix">
                            <div class="lf">房主：<span id="master-name">地瓜</span></div>
                            <div class="rf">在线人数：<span id="count">2</span>人</div>
                        </div>
                        <div class="chat-body" id="chat-messages">
                        </div>
                        <!-- <div class="banned-state">抱歉，你已被禁言！</div> -->
                        <div class="chat-bot">
                            <div class="chat-bot-bd">
                                <div class="input-group">
                                    <input type="text" id="input-text-chat" class="form-control" placeholder="Enter Text Chat" >
                                    <!-- <div contenteditable="true" class="chat-textarea form-control" placeholder="type you message"></div> -->
                                  <!-- <input type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username"> -->
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-gray" id="send-btn">发送</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
    <script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
    <!-- 从任何HTTPs域捕获屏幕！-->
    <script src="https://cdn.webrtc-experiment.com:443/getScreenId.js"></script>
    <!-- HTML5音频/视频元素的自定义布局 -->
    <script src="https://cdn.webrtc-experiment.com/getMediaElement.js"></script>

    <script>
        // .......................UI Code........................
        $(document).on('click', '#open-room', function(){
            disableInputButtons();
            connection.open($('#room-id').val(), function() {
                console.log('开启房间成功！');
            });
            connection.addStream({
                screen: true,
                oneway: true
            });
        });

        // ..................RTCMultiConnection Code.............
        let inputTextChat = $('#input-text-chat');
        inputTextChat.on('keyup', function(e){
            if (e.keyCode != 13) return;
            sendTxt();
        });
        $(document).on('click', '#send-btn', function(){
            sendTxt();
        });
        // 发送文本方法
        function sendTxt() {
            let value = inputTextChat.val();
            // removing trailing/leading whitespace
            value = value.replace(/^\s+|\s+$/g, '');
            if (!value.length) return;
            connection.send(value);
            appendDIV(value);
            inputTextChat.val('')
        }
        var chatContainer = $('#chat-messages');
        function appendDIV(event) {
            if(event.data) {
                chatContainer.append(
                    `<div class="text-lf">
                        <div class="clearfix">
                            <div class="user">${event.userid}</div>
                        </div>
                        <div class="clearfix">
                            <div class="text">${event.data}</div>
                        </div>
                    </div>`
                );
            }else {
                chatContainer.append(
                    `<div class="text-rf">
                        <div class="clearfix">
                            <div class="user">我</div>
                        </div>
                        <div class="clearfix">
                            <div class="text">${event}</div>
                        </div>
                    </div>`
                );
            }
            chatContainer.scrollTop(chatContainer[0].scrollHeight);
            // console.log(event);
            // var div = document.createElement('div');
            // div.innerHTML = event.data || event;
            // chatContainer.insertBefore(div, chatContainer.firstChild);
            // chatContainer.insertBefore(div);
            // div.tabIndex = 0;
            // div.focus();
            inputTextChat.focus();
        }
        // ......................................................
        // ..................RTCMultiConnection Code.............
        // ......................................................
        var connection = new RTCMultiConnection();
        // Using getScreenId.js to capture screen from any domain
        // You do NOT need to deploy Chrome Extension YOUR-Self!!
        connection.getScreenConstraints = function(callback) {
            getScreenConstraints(function(error, screen_constraints) {
                if (!error) {
                    screen_constraints = connection.modifyScreenConstraints(screen_constraints);
                    callback(error, screen_constraints);
                    return;
                }
                throw error;
            });
        };
        // by default, socket.io server is assumed to be deployed on your own URL
        // connection.socketURL = '/';
        // comment-out below line if you do not have your own socket.io server
        connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
        connection.socketMessageEvent = 'textchat-audio-video-screen-demo';
        connection.onopen = function(){
            document.getElementById('input-text-chat').disabled = false;
        };
        connection.onmessage  = appendDIV;
        connection.session = {
            audio: true,
            video: true,
            data: true
        };
        connection.sdpConstraints.mandatory = {
            OfferToReceiveAudio: true,
            OfferToReceiveVideo: true
        };
        connection.meVideosContainer = document.getElementById('me-videos-container');
        connection.videosContainer = document.getElementById('videos-container');
        connection.onstream = function(event) {
            if(document.getElementById(event.streamid)) {
                var existing = document.getElementById(event.streamid);
                existing.parentNode.removeChild(existing);
            }

            var width = parseInt(connection.videosContainer.clientWidth / 2) - 20;

            if(event.stream.isScreen === true) {
                width = connection.videosContainer.clientWidth - 20;
            }

            var mediaElement = getMediaElement(event.mediaElement, {
                title: event.userid,
                buttons: ['full-screen'],
                width: width,
                showOnMouseEnter: false
            });
            if(event.type === 'local') {
                connection.meVideosContainer.appendChild(mediaElement);
            }else{
                connection.videosContainer.appendChild(mediaElement);
            }
            setTimeout(function() {
                mediaElement.media.play();
            }, 5000);
            mediaElement.id = event.streamid;
        };
        connection.onstreamended = function(event) {
            var mediaElement = document.getElementById(event.streamid);
            if(mediaElement) {
                mediaElement.parentNode.removeChild(mediaElement);
            }
        };
        function disableInputButtons() {
            document.getElementById('open-room').disabled = true;
            document.getElementById('room-id').disabled = true;
            // document.getElementById('share-screen').disabled = true;
        }
        // ......................Handling Room-ID................
        var roomid = '';
        if (localStorage.getItem(connection.socketMessageEvent)) {
            roomid = localStorage.getItem(connection.socketMessageEvent);
        } else {
            roomid = connection.token();
        }
        document.getElementById('room-id').onkeyup = function() {
            localStorage.setItem(connection.socketMessageEvent, this.value);
        };
        if(roomid && roomid.length) {
            document.getElementById('room-id').value = roomid;
            localStorage.setItem(connection.socketMessageEvent, roomid);
            // auto-join-room
            // (function reCheckRoomPresence() {
            //     connection.checkPresence(roomid, function(isRoomExists) {
            //         if(isRoomExists) {
            //             connection.join(roomid);
            //             return;
            //         }
            //         setTimeout(reCheckRoomPresence, 5000);
            //     });
            // })();
            // disableInputButtons();
        }
    </script>
</body>

</html>